﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LastWorkingDays
{
	class Program
	{
		private static Int32 days = 5;
		private static List<DateTime> listHoliday = new List<DateTime>();
		private static List<DateTime> listWorkingDay = new List<DateTime>();

		static void Main( string[] args )
		{
			start0();
		}

		private static void start0()
		{
			start();
			Console.WriteLine( "Tecle Esc para para sair ou qualquer outra tecla para continuar." );
			ConsoleKeyInfo info = Console.ReadKey();
			if( info.Key != ConsoleKey.Escape )
			{
				Console.WriteLine();
				start0();
			}
		}

		private static void start()
		{
			DateTime _date = DateTime.MinValue;

			try
			{
				Console.WriteLine( "Digite uma data: " );
				_date = getDate();
				loadListHoliday();
				getLastWorkingDays( _date );
				showLastWorkingDays();
				Console.WriteLine( "Funcionou!!! Date = " + _date.ToString() );
			}
			catch( Exception ex )
			{
				Console.WriteLine();
				Console.WriteLine();
				Console.WriteLine( "#######################################################" );
				Console.WriteLine( ex.Message );
				Console.WriteLine( "#######################################################" );
				Console.WriteLine();
				Console.WriteLine();
			}
		}

		private static DateTime getDate()
		{
			DateTime _date = DateTime.MinValue;
			if( !DateTime.TryParse( Console.ReadLine(), out _date ) )
			{
				throw new Exception( "Data inválida!!!" );
			}

			return _date;
		}

		private static List<DateTime> getLastWorkingDays( DateTime date )
		{
			List<DateTime> _listDate = new List<DateTime>();
			Int32 _days = 0;

			while( _days < days )
			{
				date = date.AddDays( -1 );

				if( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday )
				{
					continue;
				}

				if( listHoliday.Contains( date ) )
				{
					continue;
				}

				listWorkingDay.Add( date );
				_days++;
			}

			return _listDate;
		}

		private static void showLastWorkingDays()
		{
			foreach( DateTime _date in listWorkingDay )
			{
				Console.WriteLine( _date.ToShortDateString() );
			}
		}

		private static void loadListHoliday()
		{
			listHoliday.Add( new DateTime( 2012, 1, 1 ) );
			listHoliday.Add( new DateTime( 2012, 2, 21 ) );
			listHoliday.Add( new DateTime( 2012, 12, 25 ) );
			listHoliday.Add( new DateTime( 2012, 12, 31 ) );
		}
	}
}
